from django.template import loader, Context
from django.http import HttpResponse, HttpResponseRedirect
from django.core import serializers
from kc.careerdept.models import *
from datetime import datetime, tzinfo, timedelta

def event_register(request):
	event_name = request.GET['event'] # release the unique name of the event
	event_instance = event.objects.get(uname=event_name) # get the event
	
	# if result=1, show the result
	try:
		show_result = request.GET['result']
		if show_result == '1':
			r = reg.objects.filter(event = event_instance)
			t = loader.get_template("result.html")
			c = Context({'event': event_instance,'regs': r})
			return HttpResponse(t.render(c))
	except:
		print 'show_result have a problem'
	
	# show event procedure
	if request.method == 'GET':
		# handle utctime, localtime and beijing time
		utctime = datetime.utcnow()
		bjnow = utctime + timedelta(hours=8)
		now = bjnow
		msg = ''
		
		# Out of time scope
		if now < event_instance.begintime:
			msg = '<font color="red"><h1>Hasn\'t Started Yet</h1><br>please wait until ' + str(_e.begintime) + '</font>'
		elif now > event_instance.endtime:
			msg = '<font color="red"><h1>The Enrollment has Ended</h1></font>'
		
		try:
			show = request.GET['show']
			if show == '1':
				msg = '' 
		except:
			pass
		
		if msg:
			t = loader.get_template("msg.html")
			return HttpResponse(t.render(Context({'msg': msg}))) 
		
		t = loader.get_template("register.html")
		c = Context({'title':event_instance.name, 'e': event_instance})
		return HttpResponse(t.render(c))
	
	elif request.method == 'POST':	
		reg_query = reg.objects.filter(event = event_instance)
		t = loader.get_template("msg.html")
		reg_instance = reg_query.filter(name = request.POST['name'])
		if len(reg_instance) > 0:
			msg = 'You have already registered, please <a href=''>go back</a> now.'
			return HttpResponse(t.render(Context({'msg': msg})))
			
		r = reg()
		r.name = request.POST['name']
		r.sid = request.POST['sid']
		r.classno = request.POST['classno']
		r.phone = request.POST['phone']
		r.email = request.POST['email']
		r.sug = request.POST['sug']
		r.timestamp = datetime.utcnow() + timedelta(hours=8)
		r.event = event_instance
		r.isChosen = False
		r.save()
		
		msg = '<h1>Thanks!</h1'
		return HttpResponse(t.render(Context({'msg': msg}))) 